import { tmp_proxy, fetchList } from "../../index";
import {
  defaultModalFormState,
  defaultModalLoading,
  defaultModalVisible,
  drawerFormState,
  operateType,
} from "../../store";
import styles from "../../index.module.less";
import { deepTreeDataOptions, tmp_tag_ids } from "../../utils";
import { dicts, systemTagsOptions, userTagsOptions } from "../../dict";
function findNodeByTagId(treeData, nodeId) {
  for (let i = 0; i < treeData.length; i++) {
    const node = treeData[i];
    if (node.tag_id === nodeId) return node;
    if (node.children && node.children.length > 0) {
      const foundNode = findNodeByTagId(node.children, nodeId);
      if (foundNode) return foundNode;
    }
  }
  return nodeId;
}

export default () => {
  watch(
    () => defaultModalVisible[0].value,
    (newValState) => {
      if (newValState === true) {
        userTagsOptions.value = deepTreeDataOptions(dicts.value.userTags);
        systemTagsOptions.value = deepTreeDataOptions(dicts.value.systemTags);
        defaultModalFormState[0].tag_ids = deepClone(drawerFormState.tag_ids);
        defaultModalFormState[0].systemIds = deepClone(
          drawerFormState.accountSystemTag
        );
      }
    }
  );
  const defineModalConfig = {
    zIndex: 1002,
    modalInstance: ref(null),
    loading: ref(false),
    maskClosable: true,
    width: "800px",
    visible: defaultModalVisible[0],
    title: ref($t("base.choiceLabel")),
    formState: defaultModalFormState[0],
    on: {
      async finish(values: any) {
        const formState = defaultModalFormState[0];
        const loading = defaultModalLoading[0];
        try {
          loading.value = true;
          formState.uid = drawerFormState.uid;
          if (operateType.value === "view") {
            const res = await userApi.updateTags({
              editId: formState.uid,
              tag_ids: [...formState.tag_ids, ...formState.systemIds],
            });
            fetchList();
          }
          nextTick(() => {
            const $formState = {
              ...formState,
              tag_ids: drawerFormState.tag_ids,
            };
            const $tmp_tag_ids = deepClone(tmp_tag_ids.value);
            tmp_tag_ids.value = $formState.tag_ids.map((item) =>
              findNodeByTagId(
                [...dicts.value.userTags, ...dicts.value.systemTags],
                item
              )
            );
            tmp_tag_ids.value = tmp_tag_ids.value.map((item) => {
              if (isNumber(item))
                return $tmp_tag_ids.find(($item) => $item.tag_id === item);
              return item;
            });
            tmp_proxy.$bus.emit("markLabel", {
              type: 0,
              formState: $formState,
            });
            loading.value = false;
            defaultModalVisible[0].value = false;
          });
        } catch (error: any) {
          message.error(error.message);
        } finally {
          loading.value = false;
        }
      },
    },
    slot: {
      extra_form_item: () => {
        const treeDataA: any = computed(() => {
          return [
            {
              label: $t("table93"),
              value: 0,
              disableCheckbox: true,
              children: userTagsOptions.value,
            },
          ];
        });

        const treeDataB: any = computed(() => {
          return [
            {
              label: $t("table94"),
              value: 0,
              disableCheckbox: true,
              children: systemTagsOptions.value,
            },
          ];
        });

        return (
          <>
            <div class={styles.label_flex}>
              <div class={styles.row}>
                <div class={styles.col}>
                  <a-tree
                    vModel:checkedKeys={defaultModalFormState[0].tag_ids}
                    defaultExpandAll={true}
                    checkable
                    height={250}
                    treeData={treeDataA.value}
                    fieldNames={{
                      children: "children",
                      title: "label",
                      key: "value",
                    }}
                    onCheck={(keys: any, event: any) => {
                      if (keys.length > 20) {
                        const index = keys.indexOf(event.node.value);
                        if (index >= 0) keys.splice(index, 1);
                        keys.splice(20);
                        defaultModalFormState[0].tag_ids = keys;
                        return message.warning(
                          $t("placeholder78") + 20 + $t("base.pieces")
                        );
                      }
                      if (!event.node.checked)
                        drawerFormState.tag_ids.push(event.node.key);
                      if (event.node.checked) {
                        const index = drawerFormState.tag_ids.findIndex(
                          (item) => +item === +event.node.key
                        );
                        if (index >= 0)
                          drawerFormState.tag_ids.splice(index, 1);
                      }
                    }}
                  ></a-tree>
                </div>
                <div class={styles.col}>
                  <a-tree
                    vModel:checkedKeys={defaultModalFormState[0].systemIds}
                    defaultExpandAll={true}
                    checkable
                    height={250}
                    treeData={treeDataB.value}
                    fieldNames={{
                      children: "children",
                      title: "label",
                      key: "value",
                    }}
                    onCheck={(keys: any, e: any) => {
                      if (keys.length > 20) {
                        const index = keys.indexOf(e.node.value);
                        if (index >= 0) keys.splice(index, 1);
                        keys.splice(20);
                        defaultModalFormState[0].systemIds = keys;
                        return message.warning(
                          $t("placeholder78") + 20 + $t("base.pieces")
                        );
                      }
                    }}
                  ></a-tree>
                </div>
              </div>
              <div class={styles.row}>
                <div class={styles.col}>
                  <span
                    class="ml5 mb8"
                    style="display: flex;justify-content: space-between;align-items: center;"
                  >
                    <span>
                      <i class="mr16">
                        {$t("base.choiced")}
                        {
                          [
                            ...defaultModalFormState[0].tag_ids,
                            ...defaultModalFormState[0].systemIds,
                          ].length
                        }
                        {$t("base.label")}
                      </i>
                    </span>

                    <s-button
                      type="link"
                      onClick={() => {
                        defaultModalFormState[0].tag_ids = [];
                        defaultModalFormState[0].systemIds = [];
                      }}
                    >
                      {$t("base.clear")}
                    </s-button>
                  </span>
                  <div style="display: flex;align-items: flex-start;justify-content: space-between;column-gap: 5px;">
                    <div style="display: flex;flex-wrap: wrap;row-gap: 8px;align-items: flex-start;justify-content: flex-start;padding-left: 5px;box-sizing: border-box;">
                      {!isEmptyType(defaultModalFormState[0].tag_ids) ? (
                        <a-tag color="blue">{$t("table93")}</a-tag>
                      ) : null}
                      {defaultModalFormState[0].tag_ids.map(
                        (value: any, index: any) => {
                          return (
                            <a-tag style="border: none;background: transparent;">
                              {
                                getItemById(userTagsOptions.value, value, {
                                  keys: ["label", "value"],
                                  values: ["label", "value"],
                                })?.label
                              }
                            </a-tag>
                          );
                        }
                      )}
                    </div>
                    {!isEmptyType(defaultModalFormState[0].tag_ids)
                      ? renderIcon("icon-jianqu", (event: any) =>
                          defaultModalFormState[0].tag_ids.splice(-1, 1)
                        )
                      : null}
                  </div>
                </div>
                <div class={styles.col}>
                  <div style="display: flex;align-items: flex-start;justify-content: space-between;column-gap: 5px;">
                    <div style="display: flex;flex-wrap: wrap;row-gap: 8px;align-items: flex-start;justify-content: flex-start;padding-left: 5px;box-sizing: border-box;">
                      {!isEmptyType(defaultModalFormState[0].systemIds) ? (
                        <a-tag color="blue">{$t("table94")}</a-tag>
                      ) : null}

                      {defaultModalFormState[0].systemIds.map(
                        (value: any, index: any) => {
                          return (
                            <a-tag style="border: none;background: transparent;">
                              {
                                getItemById(systemTagsOptions.value, value, {
                                  keys: ["label", "value"],
                                  values: ["label", "value"],
                                })?.label
                              }
                            </a-tag>
                          );
                        }
                      )}
                    </div>
                    {!isEmptyType(defaultModalFormState[0].systemIds)
                      ? renderIcon("icon-jianqu", (event: any) =>
                          defaultModalFormState[0].systemIds.splice(-1, 1)
                        )
                      : null}
                  </div>
                </div>
              </div>
            </div>
          </>
        );
      },
    },
  };
  return defineModalConfig;
};
